package thomas;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.pivot.beans.BXML;
import org.apache.pivot.beans.Bindable;
import org.apache.pivot.collections.Map;
import org.apache.pivot.util.Resources;
import org.apache.pivot.wtk.BoxPane;
import org.apache.pivot.wtk.Button;
import org.apache.pivot.wtk.ButtonPressListener;
import org.apache.pivot.wtk.Component;
import org.apache.pivot.wtk.ComponentKeyListener;
import org.apache.pivot.wtk.Container;
import org.apache.pivot.wtk.PushButton;
import org.apache.pivot.wtk.Window;

public class FocusableImageViewWindow extends Window implements Bindable {

	public static final String KEYPRESSED_MESSAGE = "Event:%-20s KeyCode:%-8d Focused Component:%s";

	@BXML private BoxPane boxPane;
	@BXML private PushButton pushButton;

	// Common Listener to be added to all Components inside the BoxPane
	private final ComponentKeyListener LISTENER = new ComponentKeyListener.Adapter() {
		@Override
		public boolean keyPressed(Component component, int keyCode, org.apache.pivot.wtk.Keyboard.KeyLocation keyLocation) {
			System.out.println(String.format(KEYPRESSED_MESSAGE , "keyPressed", keyCode, component.getName()));
			if (component == boxPane) {
				System.out.println();
			}
			return false;
		};
	};


	public FocusableImageViewWindow() {
		this(null);
	}
	public FocusableImageViewWindow(Component content) {
		super(content);
	}

	@Override
	public void initialize(Map<String, Object> namespace, URL location, Resources resources) {
		// Find all the Components inside of the BoxPane
		// and add a ComponentKeyListener each of them.
		final List<Component> components = getComponents(boxPane);
		for (Component component : components) {
			component.getComponentKeyListeners().add(LISTENER);
		}

		// Clear the focus when the PushButton is pressed
		pushButton.getButtonPressListeners().add(new ButtonPressListener() {
			@Override
			public void buttonPressed(Button button) {
				Component.clearFocus();
			}
		});
	}

	private static List<Component> getComponents(final Component component) {
		final List<Component> results = new ArrayList<Component>();
		getComponents(component, results);
		return results;
	}
	private static void getComponents(final Component component, final List<Component> results) {
		results.add(component);
		if (component instanceof Container) {
			for (Component child : (Container) component) {
				getComponents(child, results);
			}
		}
	}
}